import React from 'react';
import { Alert, Form, Input, Typography,Button,Modal } from 'antd';
import { req } from '@/common/methods';
import pub from '@/units/pub.ts';
import JSEncrypt from 'jsencrypt';

const ChangePassword: React.FC = () => {
  const [form] = Form.useForm();
  return (
    <Form
      form={form}
      name="dependencies"
      autoComplete="off"
      style={{ maxWidth: 600 }}
      layout="vertical"
      onFinish={(values)=>{
        //console.log(values);
        const rand = (Math.floor(Math.random()*61440) + 4096).toString(16);
        const pubkey = pub.getData('pubkey');
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubkey);
        const rsaPassWord = encrypt.encrypt(JSON.stringify({...values,rand}));
        req('/api/user/change_password',{data:rsaPassWord,validator:rand},'post').then(data => {
            Modal.success({
                title:'密码修改成功',
                content:<>请牢记您的新密码</>
            });
        }).catch(error => {
            Modal.error({
                title:'密码修改失败',
                content:<pre>{''+error}</pre>
            });
        });
      }}
    >
      <Alert message="修改密码" type="info" showIcon />

      <Form.Item label="原密码" name="old_password" rules={[{ required: true }]}>
        <Input type="password" />
      </Form.Item>

      <Form.Item label="新密码" name="password" rules={[{ required: true },({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('old_password') !== value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('新密码不能和旧密码一致'));
            },
          }),]}>
        <Input type="password" />
      </Form.Item>

      {/* Field */}
      <Form.Item
        label="确认新密码"
        name="password2"
        dependencies={['password']}
        rules={[
          {
            required: true,
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次新密码输入必须一致'));
            },
          }),
        ]}
      >
        <Input type="password"/>
      </Form.Item>
        <Form.Item >
            <Button type="primary" htmlType="submit">确认修改</Button>
        </Form.Item>
      {/* Render Props */}
      {/* <Form.Item noStyle dependencies={['password2']}>
        {() => (
          <Typography>
            <p>
              Only Update when <code>password2</code> updated:
            </p>
            <pre>{JSON.stringify(form.getFieldsValue(), null, 2)}</pre>
          </Typography>
        )}
      </Form.Item> */}
    </Form>
  );
};

export default ChangePassword;